package com.dao.impl;

import com.bean.Admin;
import com.bean.Class;
import com.bean.Role;
import com.dao.BaseDao;
import com.dao.ClassDao;
import com.utils.SqlUtils;

import java.util.List;
import java.util.Map;

public class ClassDaoImpl extends BaseDao implements ClassDao {
    @Override
    public List<Class> selectForPageItems(int begin, int pageSize, String content) {
        if (content == null) {
            content = "";
        }
        content = "%" + content + "%";
        String sql = "select c.`id` id,c.`name` name,count(s.`classId`) number from class c " +
                "left join student s on s.`classId`=c.`id` where c.`name` like ? " +
                "group by c.id LIMIT ?,?";
        return queryForList(Class.class, sql, content, begin, pageSize);
    }

    @Override
    public Integer selectForPageTotalCount(String content) {
        if (content == null) {
            content = "";
        }
        content = "%" + content + "%";
        String sql = "select count(1) from `class` where concat(`name`) like ?";
        Number count = (Number) queryForSingleValue(sql, content);
        return count.intValue();
    }

    @Override
    public Class selectBy(Class aClass) {
        Map.Entry<String, Object[]> entry = SqlUtils.selectBy(aClass, new String[]{"Number"});
        return queryForOne(Class.class, entry.getKey(), entry.getValue());
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        String sql = "delete from `Class` where `id` = ?";
        return update(sql, id);
    }

    @Override
    public int insert(Class record) {
        String sql = "insert into Class(`Name`) values(?)";
        return update(sql, record.getName());
    }

    @Override
    public List<Class> selectAll() {
        String sql = "select class.`id` id,class.`name` name,count(student.`classId`) number from class " +
                "left join student on student.classId=class.id group by class.id";
        return queryForList(Class.class, sql);
    }

    @Override
    public int updateByPrimaryKey(Class record) {
        String sql = "update `Class` set `name`=? where `id` = ?";
        return update(sql, record.getName(), record.getId());
    }

}
